import './index.less';

function MyFormTable({ formsColumn = [], initialValues = {}, columns = [], api = {}, ...$attrs }) {
	const [form] = Form.useForm();

	function loadData({ current, pageSize }, data) {
		if (api.page) {
			// 请求格式处理
			formsColumn.forEach((item) => {
				if (item.itemType === 'date') {
					if (item.range) {
						// 日期范围选择器
						addDateRange(data, item.name, item.prepend, formatFn(item.picker, item.showTiem));
					} else {
						// 日期选择器
						data[item.name] = data[item.name].format(formatFn(item.picker, item.showTiem));
					}
				}
			});
			return api.page({ pageNum: current, pageSize, ...data }).then((res) => ({
				total: res.data?.total,
				list: res.data?.rows
			}));
		} else {
			throw new Error('page 请求 is required!');
		}
	}

	const {
		tableProps,
		search: { submit, reset }
	} = useAntdTable(loadData, {
		form,
		defaultParams: [{ pageSize: 20 }]
	});

	return (
		<div className={`flex-col my-form-table ${$attrs.className}`}>
			{/* 减少子组件不必要的销毁，性能优化使用， */}
			{formsColumn &&
				useMemo(
					() => (
						<div className="p-10 b-radius-4 bg-var(--ant-color-bg-container) m-b-10">
							<MyForm query form={form} searchFn={submit} resetFn={reset} formsColumn={formsColumn} initialValues={initialValues} {...$attrs.Form} />
						</div>
					),
					[formsColumn, initialValues]
				)}
			<Table
				className="flex-1 overflow-hidden"
				bordered
				scroll={{ scrollToFirstRowOnChange: true, x: 'max-content', y: 'max-content' }}
				rowKey="id"
				columns={columns}
				{...tableProps}
				{...$attrs.Table}
				loading={false}
			/>
		</div>
	);
}

/***
 * 参数属性
 * @property {Array} formsColumn 生成form表单的配置数组
 * @property {Object} initialValues form表单默认值
 * @property {Array} [columns] 表格columns
 * @property {Object} [api] 页面的增、删、改、查接口 默认对应 add、remove、edit、page
 */
MyFormTable.propTypes = {
	formsColumn: propTypes.array,
	initialValues: propTypes.object,
	columns: propTypes.array,
	api: propTypes.object
};

export default memo(MyFormTable);
